﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using UcAsp.Net.Extract.Plug.Trends.BLL;
using UcAsp.Net.Extract.Plug.Trends.Model;
using UcAsp.Net.Interface;
using System.Text.RegularExpressions;
using System.Threading;
namespace UcAsp.Net.Extract.Plug.Trends
{
    public partial class UcAspControl : UserControl, IExtract
    {
        private delegate void DelegateUpdate(int i);
        private Thread t;
        private DateTime _adddatetime = DateTime.Now;
        public UcAspControl()
        {
            InitializeComponent();
            labNumber.Text = "";
            label1.Hide();
        }
        #region 属性
        /// <summary>
        /// 常规项
        /// </summary>
        /// 
        public string Security { get; set; }
        public string Image { get; set; }
        public int ID { get; set; }
        public string Title { get; set; }
        public string Tag { get; set; }
        public string IconUrl { get; set; }
        public string ArticleContent { get; set; }
        public string MetaKeyword { get; set; }
        public string MetaDescrition { get; set; }
        public string Description { get; set; }
        public DateTime AddDatetime { get { return this._adddatetime; } set { this._adddatetime = value; } }
        public bool IsRelease { get; set; }
        public bool IsRecommend { get; set; }
        public int Hot { get; set; }
        public int Rate { get; set; }
        public int CategorieID { get; set; }
        public string ShowPath { get; set; }
        public string ViewsTemp { get; set; }
        public int UserID { get; set; }
        public int Rank { get; set; }

        /// <summary>
        /// 可变文字项
        /// </summary>
        public string Note1 { get; set; }
        public string Note2 { get; set; }
        public string Note3 { get; set; }
        public string Note4 { get; set; }
        public string Note5 { get; set; }
        public string Note6 { get; set; }
        public string Note7 { get; set; }
        public string Note8 { get; set; }
        public string Note9 { get; set; }
        /// <summary>
        /// 可变数组项
        /// </summary>
        public int Int1 { get; set; }
        public int Int2 { get; set; }
        public int Int3 { get; set; }
        public int Int4 { get; set; }
        public int Int5 { get; set; }


        public double Float1 { get; set; }
        public double Float2 { get; set; }
        public double Float3 { get; set; }
        public double Float4 { get; set; }
        public double Float5 { get; set; }


        public DateTime Date1 { get; set; }
        public DateTime Date2 { get; set; }
        public DateTime Date3 { get; set; }
        public DateTime Date4 { get; set; }
        public DateTime Date5 { get; set; }
        public DateTime Date6 { get; set; }
        public DateTime Date7 { get; set; }
        public DateTime Date8 { get; set; }
        public int PageCount { get; set; }
        #endregion
        public virtual bool Execute(object id)
        { return true; }
        public virtual object Init() { return new bool(); }
        public event EventHandler Save;
        public event EventHandler SavePage;
        public event EventHandler SaveImage;
        private void btnAuto_Click(object sender, EventArgs e)
        {
            if (lbConfig.SelectedValue != null)
            {
                label1.Show();
                ParameterizedThreadStart start = new ParameterizedThreadStart(UpdateData);
                t = new Thread(start);
                t.Name = "updatedata";
                t.Start(lbConfig.SelectedValue.ToString());
            }
            else
            {
                MessageBox.Show("请选择更新类目");
            }
        }
        private void SmallContent(string url, Model.FilesConfig config)
        {
            RegexOptions options = RegexOptions.None;
            string pagecontent = HttpWebClient.GetString(url);
            //标题

            Regex pageregex = new Regex(config.TitleReg, options);
            Match match = pageregex.Match(pagecontent);
            string title = match.Groups["title"].Value;
            Title = title;
            //内容
            Regex contentregex = new Regex(config.ContentReg, options);
            Match contentmatch = contentregex.Match(pagecontent);
            string content = ClearCode(contentmatch.Groups["content"].Value, config.ClearReg);
            // richTextBox1.Text = richTextBox1.Text + "\r" + content;
            ArticleContent = content;

            if (SavePage != null)
            {
                SavePage(this, EventArgs.Empty);
            }
        }
        public void SaveSmall(string title, string iconurl, int pagenumber)
        {

            Title = title;
            //内容
            IconUrl = iconurl;
            Int1 = pagenumber;
            if (SavePage != null)
            {
                SavePage(this, EventArgs.Empty);
            }
        }
        /// <summary>
        /// 清理内容中的多余代码
        /// </summary>
        /// <param name="cotent"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        private string ClearCode(string cotent, string code)
        {
            RegexOptions options = RegexOptions.None;
            Regex regex = new Regex(code, options);
            string input = cotent;
            string replacement = "";
            string result = regex.Replace(input, replacement);

            // TODO: Do something with result
            return result;
        }

        private void UcAspControl_Load(object sender, EventArgs e)
        {
            List<Model.Config> list = BLL.Config.GetListConfig;
            lbConfig.DataSource = list;
            lbConfig.DisplayMember = "DefinedTitle";
            lbConfig.ValueMember = "DefinedName";

            this.Width = this.Parent.Width;
            this.Height = this.Parent.Height;
        }
        private void UpdateUI(int i)
        {
            labNumber.Text = "已经更新" + i.ToString() + "条";
        }
        public void UpdateData(object path)
        {
            Model.FilesConfig config = BLL.FilesConfig.GetFilesConfig(path.ToString());
            for (int p = config.PageNumber; p > 1; p--)
            {
                string urlcongent = string.Empty;
                if (p != 0)
                {
                    urlcongent = HttpWebClient.GetString(config.PageUrl.Replace("{page}", p.ToString()));
                }
                else
                {
                    urlcongent = HttpWebClient.GetString(config.Url);
                }

                //urlcongent = HttpWebClient.GetString(config.Url);
                RegexOptions options = RegexOptions.None;
                Regex regex = new Regex(config.Reg, options);
                //Match match = regex.Match(urlcongent);
                MatchCollection matches = regex.Matches(urlcongent);
                for (int j = 0; j < matches.Count; j++)
                {
                    #region 内容
                    string pageurl = matches[j].Groups["url"].Value;
                    if (pageurl.IndexOf("http://", 0) < 0)
                    {
                        pageurl = config.RootPath;
                    }
                    string pagecontent = HttpWebClient.GetString(pageurl);

                    AddDatetime = DateTime.Now; CategorieID = config.CategorieID; IsRelease = true; Image = config.ImageReg;

                    //标题
                    Regex pageregex = new Regex(config.TitleReg, options);
                    Match match = pageregex.Match(pagecontent);
                    string title = match.Groups["title"].Value;
                    Title = title;
                    //内容
                    Regex contentregex = new Regex(config.ContentReg, options);
                    Match contentmatch = contentregex.Match(pagecontent);
                    string content = contentmatch.Groups["content"].Value;
                    if (content.Length < 10)
                        continue;
                    // richTextBox1.Text = richTextBox1.Text + "\r" + ClearCode(content, config.ClearReg);
                    ArticleContent = ClearCode(content, config.ClearReg);


                    //幻灯片
                    Regex pagepic = new Regex(config.PicImageReg, options);
                    MatchCollection pagepicmatch = pagepic.Matches(pagecontent);
                    if (pagepicmatch.Count > 0)
                    {

                        if (Save != null)
                        {
                            Save(this, EventArgs.Empty);
                        }

                        for (int m = 0; m < pagepicmatch.Count; m++)
                        {
                            SaveSmall(title, pagepicmatch[m].Groups["url"].Value, m + 1);
                        }

                    }
                    else
                    {


                        //分页页码
                        Regex pagenumberregex = new Regex(config.PageReg, options);
                        MatchCollection pagenumbermatch = pagenumberregex.Matches(pagecontent);
                        
                        
                            if (Save != null)
                            {
                                Save(this, EventArgs.Empty);
                            }
                            //MessageBox.Show(this.ID.ToString());
                            PageCount = pagenumbermatch.Count + 1;
                            this.Invoke(new DelegateUpdate(UpdateUI), p);
                            if (PageCount > 1)
                            {
                                for (int i = 0; i < pagenumbermatch.Count; i++)
                                {

                                    Int1 = i + 2;
                                    if (pagenumbermatch[i].Groups["url"].Value.IndexOf("java") > -1)
                                    {
                                        Regex imgreg = new Regex(config.ImageReg, options);
                                        MatchCollection imgmatch = pagenumberregex.Matches(pagecontent);
                                        for (int m = 0; m < imgmatch.Count; m++)
                                        {
                                            SaveSmall(title, imgmatch[m].Groups["url"].Value, m + 1);
                                        }
                                    }
                                    else
                                    {
                                    SmallContent(pagenumbermatch[i].Groups["url"].Value, config);
                                     }

                                }
                            }
                        
                    }
                    ID = 0;

                    #endregion

                }

            }
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            if (t != null)
            {
                t.Abort();
            }
        }
    }
}
